require "app_config"

class BugsController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @bug_pages, @bugs = paginate :bugs, :per_page => 10
  end

  def show
    @bug = Bug.find(params[:id])
  end

  def new
    @bug = Bug.new
    @selected_project_id = 0
    @project_options = get_project_options
  end

  def create
    params[:bug][:status_id] = DEFAULT_BUG_STATUS_ID
    @bug = Bug.new(params[:bug])
    
    if @bug.save
      flash[:notice] = 'Bug was successfully created.'
      redirect_to :action => 'list'
    else
      @bug = Bug.new
      @selected_project_id = 0
      @project_options = get_project_options  
      render :action => 'new'
    end
  end

  def edit
    @bug = Bug.find(params[:id])
    @selected_project_id = @bug.project.id
    @project_options = get_project_options
    @status_options = get_status_options
  end

  def update
    @bug = Bug.find(params[:id])

    if @bug.update_attributes(params[:bug])
      flash[:notice] = 'Bug was successfully updated.'
      redirect_to :action => 'show', :id => @bug
    else
      @selected_project_id = (@bug.project.nil? ? 0 : @bug.project.id)
      @project_options = get_project_options
      @status_options = get_status_options
      render :action => 'edit'
    end
  end

  def destroy
    Bug.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
  
  private
  def get_project_options
    [["Select project", 0]] + Project.find_all.map {|i| [i.name, i.id]}
  end

  def get_status_options
    BugStatuses.find_all.map {|i| [i.name, i.id]}
  end
end
